//
//  GC_OCTool.m
//  GC_OC
//
//  Created by 曾 on 2022/1/16.
//

#import "GC_OCTool.h"

@implementation GC_OCTool
/** 获取高度 */
+(CGFloat)getHeightForLabel:(NSString*)str andFont:(UIFont*)font andWidth:(CGFloat)width
{
    UILabel* label=[[UILabel alloc]initWithFrame:CGRectMake(0,0,width,wid(10))];
    label.lineBreakMode=NSLineBreakByCharWrapping;
    label.text=str;
    label.font=font;
    label.numberOfLines=0;
    [label sizeToFit];
    CGFloat height=label.frame.size.height;
    label=nil;
    return height;

}
/** 获取宽度  */
+(CGFloat)getWidthForLabel:(NSString*)str andFont:(UIFont*)font andHeight:(CGFloat)height
{
    UILabel* label=[[UILabel alloc]initWithFrame:CGRectMake(0,0,wid(10),height)];
    label.lineBreakMode=NSLineBreakByCharWrapping;
    if([str isEqual:[NSNull null]])
    {
        label.text=@"0";
    }else
    {
        label.text=str;
    }
    label.font=font;
    label.numberOfLines=1;
    [label sizeToFit];
    CGFloat width=label.frame.size.width;
    label=nil;
    return width;
}
+(CGFloat)getMaxWidthForLabel:(NSString*)str andFont:(UIFont*)font andHeight:(CGFloat)height maxWidth:(CGFloat)maxWidth
{
    UILabel* label=[[UILabel alloc]initWithFrame:CGRectMake(0,0,wid(10),height)];
    label.lineBreakMode=NSLineBreakByCharWrapping;
    if([str isEqual:[NSNull null]])
    {
        label.text=@"0";
    }else
    {
        label.text=str;
    }
    label.font=font;
    label.numberOfLines=1;
    [label sizeToFit];
    CGFloat width=[label sizeThatFits:CGSizeMake(maxWidth, height)].width;
    label=nil;
    return width;
}
+(NSString *)getTimeFromTimestamp:(NSString*)tiemStr{

    //将对象类型的时间转换为NSDate类型

    double time =[tiemStr doubleValue];

    NSDate * myDate=[NSDate dateWithTimeIntervalSince1970:time];

    //设置时间格式

    NSDateFormatter * formatter=[[NSDateFormatter alloc]init];

    [formatter setDateFormat:@"HH:mm:ss"];

    //将时间转换为字符串

    NSString *timeStr=[formatter stringFromDate:myDate];

    return timeStr;

}
+(UIWindow*)keyWindw
{
    UIWindow* foundWindow=nil;
    NSArray* windows=[[UIApplication sharedApplication]windows];
    for(UIWindow *window in windows)
    {
        if(window.isKeyWindow)
        {
            foundWindow=window;
            break;;
        }
    }
    return  foundWindow;
}
+(NSString *)removeSpaceAndNewline:(NSString *)str
{
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}
+(NSString *)getNowTimeTimestamp{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;

    [formatter setDateStyle:NSDateFormatterMediumStyle];

    [formatter setTimeStyle:NSDateFormatterShortStyle];

    [formatter setDateFormat:@"HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

    //设置时区,这个对于时间的处理有时很重要

    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

    [formatter setTimeZone:timeZone];

    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式

    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];

    return timeSp;

}

+(UIWindow *)frontWindow
{
#if !defined(SV_APP_EXTENSIONS)
    NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
    for (UIWindow *window in frontToBackWindows) {
        BOOL windowOnMainScreen = window.screen == UIScreen.mainScreen;
        BOOL windowIsVisible = !window.hidden && window.alpha > 0;
        BOOL windowLevelSupported = (window.windowLevel >= UIWindowLevelNormal && window.windowLevel <= 0);
        BOOL windowKeyWindow = window.isKeyWindow;
        if(windowOnMainScreen && windowIsVisible && windowLevelSupported && windowKeyWindow) {
            return window;
        }
    }
#endif
    return nil;
}

+(UIImage *)OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
//    @autoreleasepool {
        UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
        [image drawInRect:CGRectMake(0,0, size.width, size.height)];
        UIImage *scaleImage=UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return scaleImage;
//    }
}

+(NSString*)filePathWithName:(NSString*)name
{
    name=[[NSString alloc]initWithFormat:@"/myData/%@.archiver",name];
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:name];
}
+(BOOL)isDirectory:(NSString *)filePath
{
      BOOL isDirectory = NO;
      [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
      return isDirectory;
}
+(NSString *)getNowTimeFromTimestamp
{

   NSDate * myDate=[NSDate now];
    //设置时间格式
    NSDateFormatter * formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    //将时间转换为字符串
    NSString *timeStr=[formatter stringFromDate:myDate];

    return timeStr;
}
+(void)setModelArrNaem:(NSArray*)array andKeyName:(NSString*)name
{
    NSString *paths =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *personsArrPath = [paths stringByAppendingString:[NSString stringWithFormat:@"/myData/%@",name]];
    NSLog(@"%@",personsArrPath);
    NSData *arrayData= [NSKeyedArchiver archivedDataWithRootObject:array];
    [arrayData writeToFile:personsArrPath atomically:YES];
    
}
+(NSArray*)getModelArrName:(NSString*)key
{
    NSString *paths =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"%@",paths);
    NSString *personsArrPath = [paths stringByAppendingString:[NSString stringWithFormat:@"/myData/%@",key]];
    NSData *resultData = [NSData dataWithContentsOfFile:personsArrPath];
    NSLog(@"%@",personsArrPath);
    return  [NSKeyedUnarchiver unarchiveObjectWithData:resultData];
}
+(NSString *)getNowFHouseTimeTimestamp
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"HH:mm"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeStr=[formatter stringFromDate:datenow];
    return timeStr;
}
+(NSString *)getNowFMMTimeTimestamp
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //自定义月份显示
    dateFormatter.monthSymbols = @[@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"11", @"12"];
    //自定义星期显示
    dateFormatter.weekdaySymbols = @[@"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六"];
    //自定义日期显示
    dateFormatter.dateFormat = @"MMMM月dd日 EEEE";
    NSString *dateStr = [dateFormatter stringFromDate:[NSDate date]];
    return dateStr;
}

+ (NSString *)timeStrWithSecTime:(NSTimeInterval)secTime
{
    NSInteger time = (NSInteger)secTime;
    
    if (time / 3600 > 0) { // 时分秒
        NSInteger hour   = time / 3600;
        NSInteger minute = (time % 3600) / 60;
        NSInteger second = (time % 3600) % 60;
        
        return [NSString stringWithFormat:@"%02zd:%02zd:%02zd", hour, minute, second];
    }else { // 分秒
        NSInteger minute = time / 60;
        NSInteger second = time % 60;
        
        return [NSString stringWithFormat:@"%02zd:%02zd", minute, second];
    }
}
+(NSString *)intervalFromLastDate:(NSString *)dateString1 toTheDate:(NSString *)dateString2
{
    NSDateFormatter *NLformatter = [[NSDateFormatter alloc] init];
    [NLformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NLformatter.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    NSCalendar *NLcalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateCom = [NLcalendar components:unit fromDate:[NLformatter dateFromString:dateString1] toDate:[NLformatter dateFromString:dateString2] options:0];
    
    
    NSString *sen=@"";
    sen = [NSString stringWithFormat:@"%ld=====%ld",dateCom.day,dateCom.year];
    NSLog(@"%@",sen);
//
//    sen=[NSString stringWithFormat:@"%@", sen];
//
//    min = [NSString stringWithFormat:@"%d", (int)cha/60%60];
//
//    min=[NSString stringWithFormat:@"%@", min];
//
//    house = [NSString stringWithFormat:@"%d", (int)cha/3600];
//
//    house=[NSString stringWithFormat:@"%@", house];

//    timeString=[NSString stringWithFormat:@"秒:%@",sen];

    return [NSString stringWithFormat:@"%ld",dateCom.day*60*60*24];

}
+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    // 判断前缀
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    // 从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    //R、G、B
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
+(void)saveFileAction:(NSString*)filePath
{
    NSArray* fileArr=[[NSUserDefaults standardUserDefaults]objectForKey:@"fileArr"];
    if(![fileArr containsObject:filePath])
    {
        NSMutableArray* array=[NSMutableArray new];
        [array addObject:filePath];
        [array addObjectsFromArray:fileArr];
        [[NSUserDefaults standardUserDefaults]setObject:array forKey:@"fileArr"];
    }
}
+(void)startTishil:(NSString*)str
{
    UIView* view=[[GC_OCTool keyWindw] viewWithTag:20200];
    if(view)
    {
        [view.layer removeAllAnimations];
        [view removeFromSuperview];
       
    }
    view=[[UIView alloc]initWithFrame:CGRectMake(0,-topHeight,SCREEN_WIDTH,topHeight)];
    view.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.7f];
    view.tag=20200;
    UILabel* label=[[UILabel alloc]initWithFrame:CGRectMake(wid(25),0,SCREEN_WIDTH-wid(25)*2,topHeight)];
    label.font=[UIFont systemFontOfSize:FontSize(12)];
    label.textColor=[UIColor whiteColor];
    label.text=str;
    label.textAlignment=NSTextAlignmentCenter;
    [label sizeToFit];
    [view addSubview:label];
    view.frame=CGRectMake((SCREEN_WIDTH-(label.frame.size.width+wid(25)*2))/2.0, (SCREEN_HEIGHT-(label.frame.size.height+hig(25)))/2.0,label.frame.size.width+wid(25)*2,label.frame.size.height+hig(30));
    label.frame=view.bounds;
    view.layer.masksToBounds=YES;
    view.layer.cornerRadius=hig(10);
    view.alpha=1;
    [[GC_OCTool keyWindw] addSubview:view];    //添加
    [UIView animateKeyframesWithDuration:3 delay:0 options:0 animations:^{
        view.alpha=0;
    } completion:^(BOOL finished) {
            if(view)
            {
                [view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
                [view.layer removeAllAnimations];
                [view removeFromSuperview];
            }
    }];
}
+(void)clearAllFilePathAction{
    NSArray* fileArr=[[NSUserDefaults standardUserDefaults]objectForKey:@"fileArr"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (NSString *file in fileArr) {
        [fileManager removeItemAtPath:file error:nil];
    }
    [[NSUserDefaults standardUserDefaults]setObject:@[] forKey:@"fileArr"];
}
-(void)clearFileAction:(NSString*)filePath
{
    [[NSUserDefaults standardUserDefaults]setObject:@[] forKey:@"fileArr"];
}
@end
